<template>
  <div class="box">
    <div class="title">筛选</div>
    <div class="listContent">
      <div v-for="(i, index) in fieldList" :key="i.key">
        <el-tree
          :props="i.fields"
          show-checkbox
          :data="[{ id: 'id', name: i.label, children: i.data }]"
          @check="handleCheckChange(index)"
          node-key="id"
          ref="tree"
        >
          <template #default="{ node, data }">
            <div v-if="data.id !== 'date'">{{ data.name }}</div>
            <div v-else>
              <el-date-picker
                type="daterange"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                v-model="dateval"
                style="width: 90%"
                size="small"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="changeDate(i.key)"
              />
            </div>
          </template>
        </el-tree>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, toRef } from 'vue'
defineOptions({
  name: 'MSearchList',
  inheritAttrs: false
})

const props = defineProps({
  fields: {
    type: Array,
    default: () => []
  }
})

interface fieldsDate {
  key: string //筛选字段名
  label: string //筛选字段标题
  fields: object //tree 数据字段
  data: any //tree 数据
}

// fields: {
//   value: 'id',
//   label: 'name',
//   children: 'children'
// },

const dateval = ref()

const fieldList: any = toRef(props, 'fields')

const emits = defineEmits(['search'])

const data: any = reactive({})

const tree = ref()
function handleCheckChange(index: number) {
  props.fields.forEach((i: any, _index) => {
    if (index === _index) {
      data[i.key] =
        tree.value[index].getCheckedKeys().indexOf('id') !== -1
          ? tree.value[index].getCheckedKeys().slice(1)
          : tree.value[index].getCheckedKeys()
    }
  })

  console.log(data)

  emits('search', data)
}

function changeDate(key: string) {
  data[key] = dateval.value
  console.log(data)
  emits('search', data)
}
</script>

<style lang="scss" scoped>
.box {
  width: 242px;
  height: 100%;
  min-height: 650px;
  border: 2px solid #e8e8e8;
  border-radius: 5px;
}
.title {
  width: 100%;
  height: 54px;
  background: #f5f6f8;
  color: #827f86;
  text-align: center;
  line-height: 54px;
}
.listContent {
  width: 100%;
  height: calc(100% - 54px);
  overflow-y: auto;
  padding: 8px;
  box-sizing: border-box;
}

:deep(.el-tree-node__content):has(.el-date-editor) {
  padding: 0 !important;
  label {
    display: none;
  }
}

:deep(.el-tree-node__content) {
  font-size: 16px;
}
</style>
